package com.mohe.shanpao.netty;

import java.security.cert.CertificateException;

import javax.net.ssl.SSLException;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;

public class TimeServer {

	static final boolean SSL = System.getProperty("ssl") != null;
	static final int PORT = Integer.parseInt(System.getProperty("port", "8009"));
	
	
	public static void main(String[] args) throws CertificateException, SSLException, InterruptedException {
		final SslContext sslCtx;
		
		if(SSL)
		{
			SelfSignedCertificate ssc = new SelfSignedCertificate();
			sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
		}
		else
		{
			sslCtx = null;
		}
		
		EventLoopGroup boss = new NioEventLoopGroup(1);
		EventLoopGroup work = new NioEventLoopGroup();
		
		try 
		{
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(boss,work).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>(){
				@Override
				protected void initChannel(SocketChannel sc) throws Exception {
					ChannelPipeline pipeline = sc.pipeline();
					if(sslCtx != null)
					{
						pipeline.addLast(sslCtx.newHandler(sc.alloc()));
					}
					
					pipeline.addLast(new TimeServerHandler());
				}
			});
			
			
			ChannelFuture f = bootstrap.bind(PORT).sync();
			f.channel().closeFuture().sync();
			
		} finally {
			work.shutdownGracefully();
			boss.shutdownGracefully();
		}
	}
	
	
}
